<?php

if ((!defined('NV_SYSTEM')) AND (!defined('NV_ADMIN'))) { Header("Location: index.php"); exit; }
if(!defined('NV_MAINFILE')) { Header("Location: index.php"); exit; }

set_magic_quotes_runtime (0);
ini_set ('magic_quotes_gpc', 'Off');
ini_set ('magic_quotes_runtime', 'Off');
ini_set ('magic_quotes_sybase', 'Off');
ini_set ('session.use_trans_sid', 0);
ini_set ('session.auto_start', '0');
ini_set ('display_errors', 0);
ini_set ('display_startup_errors', 0);
ini_set ('log_errors', 1);
ini_set ('error_reporting',2039);
ini_set ('track_errors', 1);

if(defined('FORUM_ADMIN')) {
	define('INCLUDE_PATH', '../../../');
} elseif(defined('INSIDE_MOD')) {
	define('INCLUDE_PATH', '../../');
} elseif(defined('NV_ADMIN')) {
	define('INCLUDE_PATH', '../');
} else {
	define('INCLUDE_PATH', './');
}
@require_once(INCLUDE_PATH."$datafold/config.php");
@include_once("".INCLUDE_PATH."includes/functions/security.php");

switch ($dbtype) {
	case 'MySQL':
		@require_once (INCLUDE_PATH.'includes/db/mysql.php');
		break;
	case 'mysql4':
		@require_once (INCLUDE_PATH.'includes/db/mysql4.php');
		break;
	case 'postgres':
		@require_once (INCLUDE_PATH.'includes/db/postgres7.php');
		break;
	case 'mssql':
		@require_once (INCLUDE_PATH.'includes/db/mssql.php');
		break;
	case 'msaccess':
		@require_once (INCLUDE_PATH.'includes/db/msaccess.php');
		break;
	case 'oracle':
		@require_once (INCLUDE_PATH.'includes/db/oracle.php');
		break;
	case 'mssql-odbc':
		@require_once (INCLUDE_PATH.'includes/db/mssql-odbc.php');
		break;
	case 'db2':
		@require_once (INCLUDE_PATH.'includes/db/db2.php');
		break;
}

$mainfile = 1;
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$start_time = $mtime;

$do_gzip_compress = FALSE;
/*if(isset($_GET['name']) AND $_GET['name']=="Nvmusic" AND isset($_GET['op']) AND $_GET['op']=="asxsong") { $gzip_method=0; }
if($gzip_method == 1) {
    $membagent = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : getenv('HTTP_USER_AGENT');
    if ( $phpver >= '4.0.4pl1' && ( strstr($membagent,'compatible') || strstr($membagent,'Gecko') ) ) {
       if ( extension_loaded('zlib') ) {
       @ob_start('ob_gzhandler');
       }
    }
    else if ( $phpver > '4.0' ) {
       if ( strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) {
          if ( extension_loaded('zlib') ) {
          $do_gzip_compress = TRUE;
          ob_start();
          ob_implicit_flush(0);
          header('Content-Encoding: gzip');
          }
       }
    }*/
   /* if (@extension_loaded('zlib') && !headers_sent())
		{
			ob_start('ob_gzhandler');
		}*/
//} else {
//    ob_start();
//}

function compress_output_gzip($output) {
	return gzencode($output);
}

function compress_output_deflate($output) {
	return gzdeflate($output, 9);
}

if($gzip_method == 1) {
//gzip.php v1.2 - read http://rm.pp.ru/?1.phpgzip
$PREFER_DEFLATE = false; // prefer deflate over gzip when both are supported
$FORCE_COMPRESSION = false; // force compression even when client does not report support

if(isset($_SERVER['HTTP_ACCEPT_ENCODING']))
	$AE = $_SERVER['HTTP_ACCEPT_ENCODING'];
else
	$AE = $_SERVER['HTTP_TE'];

$support_gzip = (strpos($AE, 'gzip') !== FALSE) || $FORCE_COMPRESSION;
$support_deflate = (strpos($AE, 'deflate') !== FALSE) || $FORCE_COMPRESSION;

if($support_gzip && $support_deflate) {
	$support_deflate = $PREFER_DEFLATE;
}

if ($support_deflate) {
	header("Content-Encoding: deflate");
	ob_start("compress_output_deflate");
} else{
	if($support_gzip){
		header("Content-Encoding: gzip");
		ob_start("compress_output_gzip");
	} else {
		ob_start();
	}
}
} else {
    ob_start();
}
//END gzip.php v1.2

session_name ("NVS");
session_start ();

if (!ini_get('register_globals')) {
  @import_request_variables("GPC", "");
}

$client_ip = $_SERVER['HTTP_CLIENT_IP'];
if (!strstr($client_ip,".")) $client_ip = $_SERVER['REMOTE_ADDR'];
if (!strstr($client_ip,".")) $client_ip = getenv( "REMOTE_ADDR" );
$client_ip = trim($client_ip);

if (file_exists("".INCLUDE_PATH."$datafold/config_Setban.php")) {
include_once ("".INCLUDE_PATH."$datafold/config_Setban.php");
$ip_net = explode("|",$ip_ban);
if(in_array($client_ip,$ip_net)) {
echo "<html>\n<head>\n<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\n";
echo "<title>$sitename</title>\n</head>\n\n<body>\n";
echo "<table width=\"99%\" height=\"99%\" border=\"2\" cellspacing=\"10\" cellpadding=\"10\" >\n";
echo "<tr valign =\"middle\"><td>\n";
echo "<center><img border=\"0\" src=\"".INCLUDE_PATH."images/logo.gif\"><h1><font color=\"#FF0000\">Hi and Good-bye!!!</font></h1></center>";
echo "</td>\n</tr>\n</table>\n</body>\n";
 exit;
}
}

if($eror_value==1) {
	@ini_set('display_errors', 1);
	error_reporting(E_ALL^E_NOTICE);
} else {
	@ini_set('display_errors', 0);
	error_reporting(0);
}

$db = new sql_db($dbhost, $dbuname, $dbpass, $dbname, false);
if(!$db->db_connect_id) {
    die("<br><br><center><img src=images/logo.gif><br><br><b>Xin loi, hien nay dang co su co trong viec ket noi voi may chu.<br><br>Mong ban hay quay lai site cua chung toi sau it phut.</center></b>");
}

/*------------------*/
unset($admin, $user, $adm_name, $adm_super, $admin_ar, $user_ar, $mbrow);

if(isset($_SESSION[ADMIN_COOKIE]) && !empty($_SESSION[ADMIN_COOKIE])) {
	$admin = base64_encode(addslashes(base64_decode($_SESSION[ADMIN_COOKIE])));
	if (!defined('NV_ADMIN')) {
		if(!is_array($admin)) {
			$admin_ar = explode("#:#", addslashes(base64_decode($admin)));
		}
		if (substr(addslashes($admin_ar[0]), 0, 25)!="" && $admin_ar[1]!="") {
			$admsql = "SELECT pwd, name, radminsuper FROM ".$prefix."_authors WHERE aid='".trim(substr(addslashes($admin_ar[0]), 0, 25))."' AND checknum = '$admin_ar[3]' AND agent = '$admin_ar[4]' AND last_ip = '$admin_ar[5]'";
			$admresult = $db->sql_query($admsql);
			$pass = $db->sql_fetchrow($admresult);
			$db->sql_freeresult($admresult);
			if ($pass[0] == $admin_ar[1] && !empty($pass[0]) && ($admin_ar[4] == substr (trim ($_SERVER['HTTP_USER_AGENT']), 0, 80))) {
				define('IS_ADMIN', TRUE);
				$adm_name = addslashes($pass[1]);
				$adm_super = intval($pass[2]);
				if($adm_super==1) {
					define('IS_SPADMIN', TRUE);
				}
			} else {
				unset ($_SESSION[ADMIN_COOKIE]);
			}
		}
	}
}
/*-----------------------*/

if(isset($_COOKIE[USER_COOKIE]) && !empty($_COOKIE[USER_COOKIE])) {
  $user = base64_encode(addslashes(base64_decode($_COOKIE[USER_COOKIE])));
  if (!defined('NV_ADMIN')) {
	if(!is_array($user)) {
        $user_ar = explode(":", addslashes(base64_decode($user)));
    }
    if (intval($user_ar[0])!=0 AND $user_ar[2]!="") {
		$mbsql = "SELECT * FROM ".$user_prefix."_users WHERE user_id='".intval($user_ar[0])."'";
		$mbresult = $db->sql_query($mbsql);
		$mbrow = $db->sql_fetchrow($mbresult);
		$db->sql_freeresult($mbresult);
        if(!$mbrow) {
        		setcookie(USER_COOKIE, false);
			$user = "";
			header("Location: index.php");
			exit;
        } elseif ($mbrow['user_password'] == $user_ar[2] && !empty($mbrow['user_password'])) {
            define('IS_USER', TRUE);
        }
    }
  }
}
/*-------------------*/

/*---------------*/
if($multilingual == 1) {
    if( isset($_GET['newlang']) || isset($_POST['newlang']) ) {
        $newlang = trim(( isset($_POST['newlang']) ) ? $_POST['newlang'] : $_GET['newlang']);
        if ((file_exists(INCLUDE_PATH."language/lang-".$newlang.".php")) AND (!eregi("\.","$newlang"))) {
            setcookie("lang",$newlang,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
            if (defined('IS_USER') AND (file_exists(INCLUDE_PATH."modules/Forums/language/lang_".$newlang."/lang_main.php")) AND (!eregi("\.","$newlang"))) {
            	$db->sql_query("UPDATE ".$user_prefix."_users SET user_lang='".$newlang."' WHERE user_id='".intval($user_ar[0])."'");
            }
            include(INCLUDE_PATH."language/lang-".$newlang.".php");
            $currentlang = $newlang;
        } elseif (file_exists(INCLUDE_PATH."language/lang-".$language.".php")) {
            setcookie("lang",$language,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
            include(INCLUDE_PATH."language/lang-".$language.".php");
            $currentlang = $language;
        } else {
                die("Eror! Lang file is absent!");//S13 - 23.08.06
        }
    } elseif (isset($lang)) {
        if ((file_exists(INCLUDE_PATH."language/lang-".$lang.".php")) AND (!eregi("\.","$lang"))) {
        include(INCLUDE_PATH."language/lang-".$lang.".php");
        $currentlang = $lang;
        } elseif (file_exists(INCLUDE_PATH."language/lang-".$language.".php")) {
            setcookie("lang",$language,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
            include(INCLUDE_PATH."language/lang-".$language.".php");
            $currentlang = $language;
        } else {
                die("Eror! Lang file is absent!");//S13 - 23.08.06
        }        
    } else {
        if (file_exists(INCLUDE_PATH."language/lang-".$language.".php")) {
        setcookie("lang",$language,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
        include(INCLUDE_PATH."language/lang-".$language.".php");
        $currentlang = $language;
        } else {
                die("Eror! Lang file is absent!");//S13 - 23.08.06
        } 
    }
} else {
    if (file_exists(INCLUDE_PATH."language/lang-".$language.".php")) {
    include(INCLUDE_PATH."language/lang-".$language.".php");
    $currentlang = $language;
    } else {
    die("Eror! Lang file is absent!");//S13 - 23.08.06
    }
}
/*-------------------*/

if($changtheme == 1) {
		if( isset($_GET['newsk']) || isset($_POST['newsk']) ) {
			$newsk = trim(( isset($_POST['newsk']) ) ? $_POST['newsk'] : $_GET['newsk']);
			if ((file_exists("".INCLUDE_PATH."themes/".$newsk."/theme.php")) AND (!eregi("\.","$newsk"))) {
				setcookie("clsk",$newsk,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
				$ThemeSel = $newsk;
			} elseif (file_exists("".INCLUDE_PATH."themes/".$Default_Theme."/theme.php")) {
				setcookie("clsk",$Default_Theme,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
				$ThemeSel = $Default_Theme;
			} else {
				die("".error("Eror! Theme file is absent!")."");
			}
		} elseif (isset($clsk)) {
			if ((file_exists("".INCLUDE_PATH."themes/".$clsk."/theme.php")) AND (!eregi("\.","$clsk"))) {
				$ThemeSel = $clsk;
			} elseif (file_exists("".INCLUDE_PATH."themes/".$Default_Theme."/theme.php")) {
				setcookie("clsk",$Default_Theme,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
				$ThemeSel = $Default_Theme;
			} else {
				die("".error("Eror! Skin file is absent!")."");
			}
		} else {
			if (file_exists("".INCLUDE_PATH."themes/".$Default_Theme."/theme.php")) {
				setcookie("clsk",$Default_Theme,time()+intval($live_cookie_time)*86400,$cookie_path,$cookie_domain);
				$ThemeSel = $Default_Theme;
			} else {
				die("".eror("Eror! Skin file is absent!")."");
			} 
		}
	} else {
		if (file_exists("".INCLUDE_PATH."themes/".$Default_Theme."/theme.php")) {
		$ThemeSel = $Default_Theme;
		} else {
			die("".eror("Eror! Skin file is absent!")."");
		}
	}
#############thongketruycap
if (!defined('NV_ADMIN') AND $counteract == 1) {
list($online, $statclients, $stathits) = $db->sql_fetchrow($db->sql_query("SELECT * FROM ".$prefix."_stats"));
$past = time()-60;
$onls_g = "";//khach online
$onls_m = "";//memb online
$uname = "".$client_ip."";
if(defined('IS_USER')) {
	$uname = "".intval($user_ar[0])."";
}
if($online!="") {
$online1 = explode("|",$online);
$g=0;
$g_online[0] = "";
$m=0;
$m_online[0] = "";
for($l=0; $l < sizeof($online1); $l++) {
	$online2 = explode(":",$online1[$l]);
	if(intval($online2[2]) > $past) {
		if($online2[1]==1) {
			if($onls_g!="") { $onls_g .= "|"; }
			if($online2[0]!=$uname) {
				$onls_g .= "".$online1[$l]."";
			} else {
				$onls_g .= "".$online2[0].":1:".time()."";
			}
			$g_online[$g] = $online2[0];
			$g++;
		} else {
			if($onls_m!="") { $onls_m .= "|"; }
			if($online2[0]!=$uname) {
				$onls_m .= "".$online1[$l]."";
			} else {
				$onls_m .= "".$online2[0].":0:".time()."";
			}
			$m_online[$m] = $online2[0];
			$m++;
		}
	}
}
if(!in_array($uname,$g_online) AND !in_array($uname,$m_online)) {
	if(defined('IS_USER')) {
		if($onls_m!="") { $onls_m .= "|"; }
		$onls_m .= "".$uname.":0:".time()."";
	} else {
		if($onls_g!="") { $onls_g .= "|"; }
		$onls_g .= "".$uname.":1:".time()."";
	}
}
} else {
	if(defined('IS_USER')) {
		$onls_m = "".$uname.":0:".time()."";
	} else {
		$onls_g = "".$uname.":1:".time()."";
	}
}
if($onls_g=="") { $onls_t = "".$onls_m.""; }
elseif($onls_m=="") { $onls_t = "".$onls_g.""; }
elseif($onls_g!="" AND $onls_m!="") { $onls_t = "".$onls_g."|".$onls_m.""; }

$stats_time = time() - intval($timecount);
$statcls = "";//so ip truy cap trong khoang thoi gian timecount
$stathits1 = intval($stathits);//tong so truy cap
if($statclients!="") {
$statclients_ar = explode("|",$statclients);
$m=0;
$statip[0] = "";
for($l=0;$l < sizeof($statclients_ar);$l++) {
$statclients_ar2 = explode(":",$statclients_ar[$l]);
if(intval($statclients_ar2[1]) > $stats_time) {
	if($statcls != "") { $statcls .= "|"; }
	$statcls .= "".$statclients_ar[$l]."";
	$statip[$m] = $statclients_ar2[0];
	$m++;
}
}
if(!in_array($client_ip,$statip)) {
	if($statcls != "") { $statcls .= "|"; }
	$statcls .= "".$client_ip.":".time()."";
	$stathits1++;
}
} else {
	$statcls = "".$client_ip.":".time()."";
	$stathits1++;
}
if($onls_t!="$online" || $statcls!="$statclients" || $stathits1!=$stathits) {
$db->sql_query("UPDATE ".$prefix."_stats SET online='".$onls_t."', clients='".$statcls."', hits='".$stathits1."'");
}
}

function del_online($del) {
	global $db,$prefix;
	list($online) = $db->sql_fetchrow($db->sql_query("SELECT online FROM ".$prefix."_stats"));
	$onl1 = explode("|",$online);
	$onl="";
	for($z=0; $z < sizeof($onl1); $z++) {
		$onl2 = explode(":",$onl1[$z]);
		if($onl2[0]!=$del) {
			if($onl!="") { $onl .= "|"; }
			$onl .= "".$onl1[$z]."";
		}
	}
	$db->sql_query("UPDATE ".$prefix."_stats SET online='".$onl."'");
}
###############end

$mfhandle=@opendir("".INCLUDE_PATH."includes/functions");
while ($mffile = @readdir($mfhandle)) {
	if(eregi("\.php","$mffile") AND $mffile!="mainfile.php" AND $mffile!="security.php") {//SEC05 / 18.7.2006
		@include_once("".INCLUDE_PATH."includes/functions/$mffile");
	}
}
@closedir($mfhandle);

function get_lang($module) {
	global $currentlang, $language;
	if ($module == admin) {
		if (file_exists("language/lang-$currentlang.php")) {
			@include_once("language/lang-$currentlang.php");
		} elseif (file_exists("language/lang-$language.php")) {
			@include_once("language/lang-$language.php");
		}
	} else {
		if (file_exists("modules/$module/language/lang-$currentlang.php")) {
			@include_once("modules/$module/language/lang-$currentlang.php");
		} else {
			if (file_exists("modules/$module/language/lang-$language.php")) {
				@include_once("modules/$module/language/lang-$language.php");
			}
		}
	}
}

function is_active($module) {
    global $prefix, $db;
    $module = trim($module);
    $sql = "SELECT active FROM ".$prefix."_modules WHERE title='$module'";
    $result = $db->sql_query($sql);
    $row = $db->sql_fetchrow($result);
    $act = $row['active'];
    $act = intval($act);
    if (!$result OR $act == 0) {
        return 0;
    } else {
        return 1;
    }
    $db->sql_freeresult($result);
}

function message_box() {
    global $adminfold, $adminfile, $bgcolor1, $bgcolor2, $textcolor2, $prefix, $multilingual, $currentlang, $db;
    if ($multilingual == 1) {
        $querylang = "AND (mlanguage='$currentlang' OR mlanguage='')";
    } else {
        $querylang = "";
    }
    $sql = "SELECT mid, title, content, date, expire, view FROM ".$prefix."_message WHERE active='1' $querylang";
    $result = $db->sql_query($sql);
    if ($numrows = $db->sql_numrows($result) == 0) {
        return;
    } else {
        while ($row = $db->sql_fetchrow($result)) {
            $mid = $row['mid'];
            $mid = intval($mid);
            $title = stripslashes(check_html($row['title'], "nohtml"));
            $content = stripslashes($row['content']);
            $mdate = $row['date'];
            $expire = $row['expire'];
            $expire = intval($expire);
            $view = $row['view'];
            $view = intval($view);
        if ($title != "" && $content != "") {
            if ($expire == 0) {
                $remain = _UNLIMITED;
            } else {
                $etime = (($mdate+$expire)-time())/3600;
                $etime = (int)$etime;
                if ($etime < 1) {
                    $remain = _EXPIRELESSHOUR;
                } else {
                    $remain = ""._EXPIREIN." $etime "._HOURS."";
                }
            }
            if ($view == 4 AND defined('IS_ADMIN')) {
                OpenTable();
                echo "<center><font class=\"option\" color=\"$textcolor2\"><b>$title</b></font></center><br>\n"
                    ."<font class=\"content\">$content</font>";
                    if (defined('IS_SPADMIN')) {
                    echo "<br><br><center><font class=\"content\">[ "._MVIEWADMIN." - $remain - <a href=\"".$adminfold."/".$adminfile.".php?op=editmsg&mid=$mid\">"._EDIT."</a> ]</font></center>";
                }
                CloseTable();
                echo "<br>";
            } elseif ($view == 3 AND defined('IS_USER') || defined('IS_ADMIN')) {
                OpenTable();
                echo "<center><font class=\"option\" color=\"$textcolor2\"><b>$title</b></font></center><br>\n"
                    ."<font class=\"content\">$content</font>";
                if (defined('IS_SPADMIN')) {
                    echo "<br><br><center><font class=\"content\">[ "._MVIEWUSERS." - $remain - <a href=\"".$adminfold."/".$adminfile.".php?op=editmsg&mid=$mid\">"._EDIT."</a> ]</font></center>";
                }
                CloseTable();
                echo "<br>";
            } elseif ($view == 2 AND !defined('IS_USER') || defined('IS_ADMIN')) {
                OpenTable();
                echo "<center><font class=\"option\" color=\"$textcolor2\"><b>$title</b></font></center><br>\n"
                    ."<font class=\"content\">$content</font>";
                if (defined('IS_SPADMIN')) {
                    echo "<br><br><center><font class=\"content\">[ "._MVIEWANON." - $remain - <a href=\"".$adminfold."/".$adminfile.".php?op=editmsg&mid=$mid\">"._EDIT."</a> ]</font></center>";
                }
                CloseTable();
                echo "<br>";
            } elseif ($view == 1) {
                OpenTable();
                echo "<center><font class=\"option\" color=\"$textcolor2\"><b>$title</b></font></center><br>\n"
                    ."<font class=\"content\">$content</font>";
                if (defined('IS_SPADMIN')) {
                    echo "<br><br><center><font class=\"content\">[ "._MVIEWALL." - $remain - <a href=\"".$adminfold."/".$adminfile.".php?op=editmsg&mid=$mid\">"._EDIT."</a> ]</font></center>";
                }
                CloseTable();
                echo "<br>";
            }
            if ($expire != 0) {
                $past = time()-$expire;
                if ($mdate < $past) {
                    $db->sql_query("UPDATE ".$prefix."_message SET active='0' WHERE mid='$mid'");
                }
                }
            }
        }
    }
}

function cookiedecode($user) {
    global $cookie, $prefix, $db, $user_prefix;
    $user = base64_decode($user);
    $user = addslashes($user);
    $user = htmlentities($user, ENT_QUOTES);
    $cookie = explode(":", $user);
    $sql = "SELECT user_password FROM ".$user_prefix."_users WHERE username='$cookie[1]'";
    $result = $db->sql_query($sql);
    $row = $db->sql_fetchrow($result);
    $pass = $row['user_password'];
    if ($cookie[2] == $pass && $pass != "") {
        return $cookie;
    } else {
        unset($user);
        unset($cookie);
    }
}

function getusrinfo($user) {
    global $userinfo, $user_prefix, $db;
    $user2 = base64_decode($user);
    $user2 = addslashes($user2);
    $user3 = explode(":", $user2);
    $sql = "SELECT * FROM ".$user_prefix."_users WHERE username='$user3[1]' AND user_password='$user3[2]'";
    $result = $db->sql_query($sql);
    if ($db->sql_numrows($result) == 1) {
        $userinfo = $db->sql_fetchrow($result);
    }
    return $userinfo;
}

function FixQuotes ($what = "") {
    $what = ereg_replace("'","''",$what);
    while (eregi("\\\\'", $what)) {
        $what = ereg_replace("\\\\'","'",$what);
    }
    return $what;
}

/*********************************************************/
/* text filter                                                 */
/*********************************************************/

function check_words($Message) {
    global $CensorMode, $EditedMessage, $datafold;
    include("".INCLUDE_PATH."$datafold/config.php");
    $EditedMessage = $Message;
    if ($CensorMode != 0) {
        if (is_array($CensorList)) {
            $Replace = $CensorReplace;
            if ($CensorMode == 1) {
                for ($i = 0; $i < count($CensorList); $i++) {
                    $EditedMessage = eregi_replace("$CensorList[$i]([^a-zA-Z0-9])","$Replace\\1",$EditedMessage);
                }
            } elseif ($CensorMode == 2) {
                for ($i = 0; $i < count($CensorList); $i++) {
                    $EditedMessage = eregi_replace("(^|[^[:alnum:]])$CensorList[$i]","\\1$Replace",$EditedMessage);
                }
            } elseif ($CensorMode == 3) {
                for ($i = 0; $i < count($CensorList); $i++) {
                    $EditedMessage = eregi_replace("$CensorList[$i]","$Replace",$EditedMessage);
                }
            }
        }
    }
    return ($EditedMessage);
}

function delQuotes($string){
    /* no recursive function to add quote to an HTML tag if needed */
    /* and delete duplicate spaces between attribs. */
    $tmp="";        # string buffer
    $result=""; # result string
    $i=0;
    $attrib=-1; # Are us in an HTML attrib ?   -1: no attrib   0: name of the attrib   1: value of the atrib
    $quote=0;        # Is a string quote delimited opened ? 0=no, 1=yes
    $len = strlen($string);
    while ($i<$len) {
        switch($string[$i]) { # What car is it in the buffer ?
            case "\"": #"        # a quote.
                if ($quote==0) {
                    $quote=1;
                } else {
                    $quote=0;
                    if (($attrib>0) && ($tmp != "")) { $result .= "=\"$tmp\""; }
                    $tmp="";
                    $attrib=-1;
                }
                break;
            case "=":                # an equal - attrib delimiter
                if ($quote==0) {  # Is it found in a string ?
                    $attrib=1;
                    if ($tmp!="") $result.=" $tmp";
                    $tmp="";
                } else $tmp .= '=';
                break;
            case " ":                # a blank ?
                if ($attrib>0) {  # add it to the string, if one opened.
                    $tmp .= $string[$i];
                }
                break;
            default:                # Other
                if ($attrib<0)          # If we weren't in an attrib, set attrib to 0
                $attrib=0;
                $tmp .= $string[$i];
                break;
        }
        $i++;
    }
    if (($quote!=0) && ($tmp != "")) {
        if ($attrib==1) $result .= "=";
        /* If it is the value of an atrib, add the '=' */
        $result .= "\"$tmp\"";        /* Add quote if needed (the reason of the function ;-) */
    }
    return $result;
}

function check_html ($str, $strip="") {
   global $datafold;
    /* The core of this code has been lifted from phpslash */
    /* which is licenced under the GPL. */
    include("".INCLUDE_PATH."$datafold/config.php");
    if ($strip == "nohtml")
        $AllowableHTML=array('');
        $str = stripslashes($str);
        $str = eregi_replace("<[[:space:]]*([^>]*)[[:space:]]*>",'<\\1>', $str);
            // Delete all spaces from html tags .
        $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>",'<a href="\\1">', $str);
            // Delete all attribs from Anchor, except an href, double quoted.
        $str = eregi_replace("<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>", '', $str);
            // Delete all img tags
        $str = eregi_replace("<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>", '', $str);
            // Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
        $tmp = "";
        while (ereg("<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>",$str,$reg)) {
                $i = strpos($str,$reg[0]);
                $l = strlen($reg[0]);
                if ($reg[1][0] == "/") $tag = strtolower(substr($reg[1],1));
                else $tag = strtolower($reg[1]);
                if ($a = $AllowableHTML[$tag])
                        if ($reg[1][0] == "/") $tag = "</$tag>";
                        elseif (($a == 1) || ($reg[2] == "")) $tag = "<$tag>";
                        else {
                          # Place here the double quote fix function.
                          $attrb_list=delQuotes($reg[2]);
                          // A VER
                          $attrb_list = ereg_replace("&","&amp;",$attrb_list);
                          $tag = "<$tag" . $attrb_list . ">";
                        } # Attribs in tag allowed
                else $tag = "";
                $tmp .= substr($str,0,$i) . $tag;
                $str = substr($str,$i+$l);
        }
        $str = $tmp . $str;
        return $str;
        exit;
        /* Squash PHP tags unconditionally */
        $str = ereg_replace("<\?","",$str);
        return $str;
}

function filter_text($Message, $strip="") {
    global $EditedMessage;
    check_words($Message);
    $EditedMessage=check_html($EditedMessage, $strip);
    return ($EditedMessage);
}

function nl2brStrict($text) {
   $text = trim($text);
   $text = ereg_replace(" \r\n","\r\n",$text);
   $text = str_replace("\r", '', $text);
   $text = preg_replace('/(?<!>)\n/', "<br />", $text);
   return $text;
}

/*********************************************************/
/* formatting stories                                         */
/*********************************************************/

function formatTimestamp($time,$ht=1) {
    global $datetime, $hourdiff, $htg1, $htg2;
    ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})", $time, $datetime); 
    $datetime = mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]); 
    $timeadjust = ($hourdiff * 60);
    $datetime = $datetime+$timeadjust;
    if ($ht == 2) { $xht = $htg2; } else { $xht = $htg1; }
    $datetime = date("$xht", $datetime); 
    return($datetime);
}

function viewtime($vtime,$ht) {
    global $hourdiff, $htg1, $htg2;
    if ($ht == 2) { $xht = $htg2; } else { $xht = $htg1; }
    $timeadjust = ($hourdiff * 60);
    $viewtime = date("$xht", $vtime + $timeadjust);
    return($viewtime);
}

function generate_page($base_url, $num_items, $per_page, $start_item, $add_prevnext_text = TRUE) {
    $total_pages = ceil($num_items/$per_page);
    if ($total_pages == 1) { return ''; }

    @$on_page = floor($start_item / $per_page) + 1;
    $page_string = '';
    if($total_pages > 10) {
    $init_page_max = ($total_pages > 3) ? 3 : $total_pages;
    for($i = 1; $i < $init_page_max + 1; $i++) {
    $page_string .= ($i == $on_page) ? '<b>'.$i.'</b>' : '<a href="'.$base_url."&amp;page=".(($i - 1) * $per_page).'">'.$i.'</a>';
    if ($i <  $init_page_max) { $page_string .= ", "; }
    }
    if ($total_pages > 3) {
    if ($on_page > 1  && $on_page < $total_pages) {
    $page_string .= ($on_page > 5) ? ' ... ' : ', ';
    $init_page_min = ($on_page > 4) ? $on_page : 5;
    $init_page_max = ($on_page < $total_pages - 4) ? $on_page : $total_pages - 4;
    for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++) {
    $page_string .= ($i == $on_page) ? '<b>'.$i.'</b>' : '<a href="'.$base_url. "&amp;page=" .(($i - 1) * $per_page).'">'.$i.'</a>';
    if ($i <  $init_page_max + 1) { $page_string .= ', '; }
    }
    $page_string .= ($on_page < $total_pages - 4) ? ' ... ' : ', ';
    }
    else { $page_string .= ' ... '; }

    for($i = $total_pages - 2; $i < $total_pages + 1; $i++) {
    $page_string .= ($i == $on_page) ? '<b>'.$i.'</b>'  : '<a href="'.$base_url. "&amp;page=" . (($i - 1) * $per_page).'">'.$i.'</a>';
    if( $i <  $total_pages ) { $page_string .= ", "; }
    }
    }
    } else {
    for($i = 1; $i < $total_pages + 1; $i++) {
    $page_string .= ($i == $on_page) ? '<b>'.$i.'</b>' : '<a href="'.$base_url. "&amp;page=" . (($i - 1) * $per_page).'">'.$i.'</a>';
    if ($i <  $total_pages) { $page_string .= ', '; }
    }
    }
    if ($add_prevnext_text) {
    if ($on_page > 1) {
    $page_string = ' <a href="'.$base_url. "&amp;page=" . (($on_page - 2) * $per_page).'">'. _PAGEPREV.'</a>&nbsp;&nbsp;' . $page_string;
    }
    if ($on_page < $total_pages) {
    $page_string .= '&nbsp;&nbsp;<a href="'.$base_url. "&amp;page=" . ($on_page * $per_page).'">'. _PAGENEXT.'</a>';
    }
    }
    $page_string = _PAGESNUM . ' ' . $page_string;
    return $page_string;
}

function removecrlf($str) {
    // Function for Security Fix by Ulf Harnhammar, VSU Security 2002
    // Looks like I don't have so bad track record of security reports as Ulf believes
    // He decided to not contact me, but I'm always here, digging on the net
    return strtr($str, "\015\012", ' ');
}

function info_exit($info) {
	$info = stripslashes(FixQuotes($info));
	include(INCLUDE_PATH."header.php");
	OpenTable();
	echo "<br><center><b>".$info."</b></center><br>";
	CloseTable();
	include(INCLUDE_PATH."footer.php");
	exit();
}

function select_language($sellang) {
	$handle=opendir("".INCLUDE_PATH."language");
	while ($file = readdir($handle)) {
		if (preg_match("/^lang\-(.+)\.php/", $file, $matches)) {
			$langFound = $matches[1];
			$languageslist .= "$langFound ";
		}
	}
	closedir($handle);
	$languageslist = explode(" ", $languageslist);
	sort($languageslist);
	for ($i=0; $i < sizeof($languageslist); $i++) {
		if($languageslist[$i]!="") {
			$select_lang .=  "<option value='".$languageslist[$i]."' ";
			if($languageslist[$i]==$sellang) $select_lang .= "selected";
			$select_lang .= ">".ucfirst($languageslist[$i])."</option>";
		}
	}
	return $select_lang;
}


if ($disable_site) {
    if (!eregi("".$adminfile.".php", $_SERVER['SCRIPT_NAME']) && !defined('IS_ADMIN') && $name!= "Your_Account") {
        include("header.php");
        OpenTable();
        echo"<center><h1>"._CLOSESITE."</h1></center>\n".stripslashes(html_entity_decode($disable_message))."\n";
        CloseTable();
        include("footer.php");
        die();
    }
}

function aleditor($content,$val,$ewidth,$eheight) {
	global $currentlang;
	if($currentlang=="vietnamese") { $lag = "vn"; }
	else { $lag = "en"; }
	$sw = new SpawEditor("$content", $val);	
	SpawConfig::setStaticConfigValue('default_height',$eheight);
	SpawConfig::setStaticConfigValue('default_lang',$lag);
     $sw->show();
}

function nvheader($filename) {
       echo '<script type="text/javascript">';
       echo 'window.location.href="'.$filename.'";';
       echo '</script>';
       echo '<noscript>';
       echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
       echo '</noscript>';
}

switch($gfx) {

	case "gfx":
	$datekey = date("F j");
    $rcode = hexdec(md5($_SERVER[HTTP_USER_AGENT] . $sitekey . $random_num . $datekey));
    $code = substr($rcode, 2, 6);
    $image = ImageCreateFromJPEG("".INCLUDE_PATH."images/code_bg.jpg");
    if (!$image) {
        $image  = imagecreate (73, 15);
        $bgc = imagecolorallocate ($image, 240, 240, 240);
        imagefilledrectangle ($image, 0, 0, 73, 15, $bgc);
    }
    $text_color = ImageColorAllocate($image, 50, 50, 50);
    Header("Content-type: image/jpeg");
    ImageString ($image, 5, 11, 1, $code, $text_color);
    ImageJPEG($image, '', 90);
    ImageDestroy($image);
    die();
	break;

}

?>